package com.example.sellqq.controller;

import com.example.sellqq.constant.ResourceConstant;
import com.example.sellqq.domain.User;
import com.example.sellqq.service.UserService;
import com.example.sellqq.util.ZipUtils;
import com.example.sellqq.vo.ResponseVO;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.Objects;

/**
 * @Author: thekernel
 * @Date: 2020/4/20 00:09
 * @Version: 1.0
 * @Description:
 */
@Api(value = "用户Controller")
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiIgnore
    @GetMapping("hello")
    public @ResponseBody
    String index() {
        return "Hello User !!!";
    }

    @ApiOperation(value = "添加卖号信息", notes = "卖号信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qq", value = "QQ号", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "imageFront", value = "身份证正面图片URL", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "imageBack", value = "身份证反面图片URL", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "imageHand", value = "手持身份证图片URL", required = true, dataTypeClass = String.class),
    })
    @PostMapping("sell")
    public @ResponseBody
    ResponseVO addSellInfo(@Valid @ModelAttribute User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseVO.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }

        return this.userService.addSellInfo(user);
    }

    @ApiOperation(value = "上传图片", notes = "图片信息")
    @PostMapping(value = "image", headers = "content-type=multipart/form-data")
    public @ResponseBody
    ResponseVO uploadImage(@ApiParam(name = "image", value = "图片文件") MultipartFile image) throws IOException {
        return this.userService.uploadImage(image);
    }

    @ApiOperation(value = "获取图片", notes = "根据url获取图片")
    @GetMapping(value = "/image/{image}", produces = MediaType.IMAGE_JPEG_VALUE)
    public @ResponseBody
    byte[] getImage(@PathVariable(name = "image") String image) throws IOException {
        String filename = ResourceConstant.ABSOLUTE_IMAGE_PATH + image;
        File file = new File(filename);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }

    @ApiOperation(value = "获取所有卖号信息", notes = "卖号信息")
    @GetMapping(value = "all")
    public @ResponseBody
    ResponseVO getAll() {
        return this.userService.getAllSellInfo();
    }

    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @GetMapping(value = "excel/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        HSSFWorkbook workBook = this.userService.exportExcel();
        workBook.write(byteArrayOutputStream);
        response.setContentLength(byteArrayOutputStream.size());
        // 准备将Excel的输出流通过response输出到页面下载
        // 八进制输出流
        response.setContentType("application/octet-stream");
        // 这后面可以设置导出Excel的名称，此例中名为export.xls
        response.setHeader("Content-disposition", "attachment;filename=export.xls");

        // 刷新缓冲
        response.flushBuffer();

        // workbook将Excel写入到response的输出流中，供页面下载
        workBook.write(response.getOutputStream());
    }

    @ApiOperation(value = "导出Images", notes = "导出Images")
    @GetMapping(value = "image/export")
    public void exportImage(HttpServletResponse response) {
        String zipFilePath = "data/image";
        String fileName = "images";
        boolean flag = ZipUtils.folderToZip(zipFilePath, "data/", fileName);
        if (flag) {
            File images = new File("data/images.zip");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=images.zip");
            response.setContentLengthLong(images.length());
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;

            try {
                fis = new FileInputStream(images);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("文件打包失败!");
        }
    }

    @ApiOperation(value = "删除Images", notes = "删除Images")
    @DeleteMapping("/image")
    public @ResponseBody
    ResponseVO deleteAllImages() {
        return this.userService.deleteAllImage();
    }

}
